package com.moblie.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.moblie.constant.RedisConstant;
import com.moblie.domain.Evaluate;
import com.moblie.dao.EvaluateDao;
import com.moblie.service.EvaluateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*
点评相关的service实现类
* */
// 用dubbo提供的Service注解,并制定相关接口
@Service(interfaceClass = EvaluateService.class)
// 在设置事务相关的注解
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
public class EvaluateServiceImpl implements EvaluateService {


    // 自动注入dao接口
    @Autowired
    private EvaluateDao evaluateDao;
    // 自动注入jedispool
    @Autowired
    private JedisPool jedisPool;

    // 发表评论,
    @Override
    public void publish(Evaluate evaluate) {
        // 1.调用dao中的publish方法,将评论信息存入评论表中
        evaluateDao.publish(evaluate);
        // 2.获取evaluate中imgs属性
        List<String> imgs = evaluate.getImgs();

        // 遍历该imgs的集合
        for (String img : imgs) {
            // 3.调用dao中的publishImgs方法,参数为img和evaluate对象中自动生成的id值,封装为map集合
            Map<String, Object> map = new HashMap<>();
            map.put("evaluateId", evaluate.getId());
            map.put("img", img);
            evaluateDao.publishImgs(map);
            // 4.如果存储成功后,将该图片存入redis的evaluatePicDbResources中
            jedisPool.getResource().sadd(RedisConstant.EVALUATE_PIC_DB_RESOURCES, img);
        }

        // 4.评价成功,在往商家和评价中间表中添加数据,参数为点评对象的id和商家id,封装为map集合
        Map<String, Object> map1 = new HashMap<>();
        map1.put("evaluateId", evaluate.getId());
        map1.put("merchantId", evaluate.getMerchantId());
        evaluateDao.addEvaluateAndMerchant(map1);

        // 5. 评价完,从点评表查询每一项对应的平均分,以及该商家总点评数,参数为商家id,返回map集合
       Map<String,Object> map2 = evaluateDao.getAvgPointsAndTotalEvaluate(evaluate.getMerchantId());
        // 6.在设置商家表的平均分,参数为该list集合和商家id,封装为map集合
        map2.put("merchantId",evaluate.getMerchantId());
        evaluateDao.setAvgPointsAndTotalEvaluate(map2);

    }
}
